package com.zxc;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class MyDelayedTask implements Delayed {

    private long executeTime;
    private String name;

    @Override
    public String toString() {
        return "MyDelayedTask{" +
                "executeTime=" + executeTime +
                ", name='" + name + '\'' +
                '}';
    }

    public MyDelayedTask(int executeTime, String name) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, executeTime);
        this.executeTime =  instance.getTimeInMillis();
        this.name = name;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        Calendar instance = Calendar.getInstance();
        return unit.convert(Math.max(0, executeTime - instance.getTimeInMillis()), unit);

    }

    @Override
    public int compareTo(Delayed o) {
        long l = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return l == 0 ? 0 : (l > 1 ? 1 : -1);
    }

    public static void main(String[] args) {

        DelayQueue<MyDelayedTask> tasks = new DelayQueue<>();
        tasks.add(new MyDelayedTask(10, "张三"));
        tasks.add(new MyDelayedTask(5, "李四"));
        tasks.add(new MyDelayedTask(15, "王五"));
        while (tasks.size() != 0) {
            System.out.println(new Date());
            MyDelayedTask poll = tasks.poll();
            if(poll!=null){

                System.out.println(new Date() + ":" + poll);
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
